import 'package:barcode_scan/barcode_scan.dart';
import 'package:factoryside/api/api.dart';
import 'package:factoryside/bean/acc_order.dart';
import 'package:factoryside/bean/audit_acc_entity.dart';
import 'package:factoryside/bean/factory_address_entity.dart';
import 'package:factoryside/generated/json/factory_address_entity_helper.dart';
import 'package:factoryside/utils/request_util.dart';
import 'package:factoryside/utils/utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_my_picker/common/date.dart';
import 'package:flutter_my_picker/flutter_my_picker.dart';

//审核发货界面
class AccAuditDetailPage extends StatefulWidget {
  AccOrderDataData data;

  AccAuditDetailPage(this.data);

  @override
  State<StatefulWidget> createState() {
    return _AccAuditDetailState();
  }
}

class _AccAuditDetailState extends State<AccAuditDetailPage> {
  TextEditingController oldReturnRequestCtr = TextEditingController();
  TextEditingController checkRemarksCtr = TextEditingController();
  TextEditingController expressNoCtr = TextEditingController();

   List<FactoryAddressEntity> items=[];


  String AccessoryAndServiceApplyState;//1通过 -1拒绝
  String DeliverGoodsType;//1现在发货 2延迟发货
  String DeliverGoodsTime;//预估发货时间
  String AccessoryID;
  String RecipientType;
  String IsReturn;
  String SendAddress;
  String AddressBack;
  String PostPayType;
  String OldReturnRequest;
  String CheckRemarks;
  String ExpressNo;

  var workAddr;
  var userAddr;

  var timeStr;

  String AccessoryState;//0厂家寄件
  String State;//配件状态

  AuditAccEntity _auditAccEntity;

  @override
  void dispose() {
    super.dispose();
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    AccessoryState = widget.data.accessoryState;
    State = widget.data.state;
    workAddr = widget.data.workerProvince +
        widget.data.workerCity +
        widget.data.workerArea +
        widget.data.workerDistrict +
        widget.data.workerAddress +
        '(${widget.data.workerName} 收) ${widget.data.workerPhone}';
    userAddr = widget.data.address +
        '(${widget.data.userName} 收) ${widget.data.phone}';
    if(widget.data.recipientType=="1"){
      _userSelected = true;
      _workerSelected = false;
      SendAddress=userAddr;
    }else{
      _userSelected = false;
      _workerSelected = true;
      SendAddress=workAddr;
    }
    RequestUtil.post(Api.getFactoryAddress, {}).then((value) => this.setState(() {
      List tempList=value['Data'];
      List<FactoryAddressEntity> addrList=[];
      tempList.forEach((element) {
        addrList.add(factoryAddressEntityFromJson(FactoryAddressEntity(), element));
      });
      items = addrList;
      if(items.length>0){
        AddressBack='${items[0].value}';
      }
    }));
  }
  ///通过拒绝
  bool _passSelected = false;
  bool _rejectSelected = false;
  ///是否延迟发货
  bool _delaySelected = false;
  bool _unDelaySelected = false;
  ///师傅收件还是用户收件
  bool _userSelected = true;
  bool _workerSelected = false;

  ///是否需要返件
  bool _yesSelected = false;
  bool _noSelected = false;

  ///到付现付
  bool _dSelected = false;
  bool _xSelected = false;

  Future _scan() async {
    try {
      String barcode = await BarcodeScanner.scan();
      setState(() {
        expressNoCtr.text=barcode;
        return this.ExpressNo = barcode;
      });
    } on PlatformException catch (e) {
      if (e.code == BarcodeScanner.CameraAccessDenied) {
        setState(() {
//          return expressNoCtr.text = 'The user did not grant the camera permission!';
          return expressNoCtr.text = '未允许相机权限!';
        });
      } else {
        setState(() {
          return expressNoCtr.text = 'Unknown error: $e';
        });
      }
    } on FormatException {
      setState(() => expressNoCtr.text =
//      'null (User returned using the "back"-button before scanning anything. Result)');
      '');
    } catch (e) {
      setState(() => expressNoCtr.text = 'Unknown error: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
        appBar: AppBar(
          //导航栏
          title: Text(widget.data.accessoryNo),
        ),
        body: items.length>0?Column(
          children: [
            Expanded(
              child: ListView(
                children: [
                  Container(
                    color: Colors.white,
                    child: Column(
                      children: [
                        buildContainer_base(),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            Container(
              color: Colors.transparent,
              width: double.infinity,
              height: 50,
              margin: EdgeInsets.all(10),
              child: ElevatedButton(
                onPressed: () {
                  _auditAccEntity=AuditAccEntity();
                  _auditAccEntity.accessoryID='${widget.data.accessoryId}';
                  var url=Api.auditAccessory;
                  if (State!='1') {
                    if(!_passSelected&&!_rejectSelected){
                                        showToast('请选择是否通过！');
                                        return;
                                      }
                    if (_passSelected) {
                      _auditAccEntity.accessoryAndServiceApplyState='1';
                      if(!_delaySelected&&!_unDelaySelected){
                        showToast('请选择是否延迟发货！');
                        return;
                      }
                      if (_unDelaySelected) {//现在发货
                        _auditAccEntity.deliverGoodsType='1';
                        if(!_yesSelected&&!_noSelected){
                                                                showToast('请选择是否需要返件！');
                                                                return;
                                                              }
                        if(_yesSelected){
                          if(AddressBack==null){
                            showToast('请选择返件地址！');
                            return;
                          }
                          if(!_dSelected&&!_xSelected){
                            showToast('请选择到付还是现付！');
                            return;
                          }
                        }
                        _userSelected?RecipientType="1":RecipientType="2";
                        _yesSelected?IsReturn="1":IsReturn="2";
                        _dSelected?PostPayType="1":PostPayType="2";
                        OldReturnRequest=oldReturnRequestCtr.text;
                        CheckRemarks=checkRemarksCtr.text;
                        ExpressNo=expressNoCtr.text;
                        if(ExpressNo.isEmpty){
                          showToast('请输入快递单号！');
                          return;
                        }
                        _auditAccEntity.recipientType=RecipientType;
                        _auditAccEntity.isReturn=IsReturn;
                        _auditAccEntity.postPayType=PostPayType;
                        _auditAccEntity.oldReturnRequest=OldReturnRequest;
                        _auditAccEntity.checkRemarks=CheckRemarks;
                        _auditAccEntity.expressNo=ExpressNo;
                      }else{
                        _auditAccEntity.deliverGoodsType='2';
                        if(timeStr==null){
                          showToast('请选择发货时间！');
                          return;
                        }
                        _auditAccEntity.deliverGoodsTime=timeStr;
                      }
                    }else{
                      _auditAccEntity.accessoryAndServiceApplyState='-1';
                      CheckRemarks=checkRemarksCtr.text;
                      if(CheckRemarks.isEmpty){
                        showToast('请输入拒绝原因！');
                        return;
                      }
                      _auditAccEntity.checkRemarks=CheckRemarks;
                    }
                  }else if(State=='1'){

                    url=Api.fillInDeliverGoods;

                    if(!_yesSelected&&!_noSelected){
                      showToast('请选择是否需要返件！');
                      return;
                    }
                    if(_yesSelected){
                      if(AddressBack==null){
                        showToast('请选择返件地址！');
                        return;
                      }
                      if(!_dSelected&&!_xSelected){
                        showToast('请选择到付还是现付！');
                        return;
                      }
                    }
                    _userSelected?RecipientType="1":RecipientType="2";
                    _yesSelected?IsReturn="1":IsReturn="2";
                    _dSelected?PostPayType="1":PostPayType="2";
                    OldReturnRequest=oldReturnRequestCtr.text;
                    CheckRemarks=checkRemarksCtr.text;
                    ExpressNo=expressNoCtr.text;
                    if(ExpressNo.isEmpty){
                      showToast('请输入快递单号！');
                      return;
                    }
                    _auditAccEntity.recipientType=RecipientType;
                    _auditAccEntity.isReturn=IsReturn;
                    _auditAccEntity.postPayType=PostPayType;
                    _auditAccEntity.oldReturnRequest=OldReturnRequest;
                    _auditAccEntity.checkRemarks=CheckRemarks;
                    _auditAccEntity.expressNo=ExpressNo;
                  }
                  RequestUtil.post(
                      url,_auditAccEntity.toJson()
                  ).then((value) => this.setState(() {
                    if(value['Data']['code']==0){
                      showToast('提交成功');
                      Navigator.pop(context,"提交成功");
                    }else{
                      showToast(value['Data']['msg']);
                    }
                  }));
                },
                child: Text(
                  '提交'
                )
              ),
            )
          ],
        ):Center(child: CircularProgressIndicator())
    );
  }

  ///基本信息
  Container buildContainer_base() {
    return Container(
        margin: EdgeInsets.symmetric(vertical: 10),
        padding: EdgeInsets.all(10),
        color: Colors.white,
        child: Column(
          children: [
            State!='1'?Column(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    // 复选框
                    GestureDetector(
                      child: Row(
                        children: [
                          Checkbox(
                              value: _passSelected,
                              onChanged: (value) {
                                setState(() {
                                  _passSelected = true;
                                  _rejectSelected = false;
                                });
                              }),
                          Text('通过',
                              textAlign: TextAlign.end,
                              style: TextStyle(
                                  fontSize: 16,
                                  color: Colors.black,
                                  fontWeight: FontWeight.bold)),
                        ],
                      ),
                      onTap: () {
                        setState(() {
                          _passSelected = true;
                          _rejectSelected = false;
                        });
                      },
                    ),
                    GestureDetector(
                      child: Row(
                        children: [
                          Checkbox(
                              value: _rejectSelected,
                              onChanged: (value) {
                                setState(() {
                                  _passSelected = false;
                                  _rejectSelected = true;
                                });
                              }),
                          Text('不通过',
                              textAlign: TextAlign.end,
                              style: TextStyle(
                                  fontSize: 16,
                                  color: Colors.black,
                                  fontWeight: FontWeight.bold)),
                        ],
                      ),
                      onTap: () {
                        setState(() {
                          _passSelected = false;
                          _rejectSelected = true;
                        });
                      },
                    ),
                  ],
                ),
                Visibility(
                  visible: _passSelected,
                  child: Column(
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          // 复选框
                          GestureDetector(
                            child: Row(
                              children: [
                                Checkbox(
                                    value: _unDelaySelected,
                                    onChanged: (value) {
                                      setState(() {
                                        _unDelaySelected = true;
                                        _delaySelected = false;
                                      });
                                    }),
                                Text('现在发货',
                                    textAlign: TextAlign.end,
                                    style: TextStyle(
                                        fontSize: 16,
                                        color: Colors.black,
                                        fontWeight: FontWeight.bold)),
                              ],
                            ),
                            onTap: () {
                              setState(() {
                                _unDelaySelected = true;
                                _delaySelected = false;
                              });
                            },
                          ),
                          GestureDetector(
                            child: Row(
                              children: [
                                Checkbox(
                                    value: _delaySelected,
                                    onChanged: (value) {
                                      setState(() {
                                        _unDelaySelected = false;
                                        _delaySelected = true;
                                      });
                                    }),
                                Text('延迟发货',
                                    textAlign: TextAlign.end,
                                    style: TextStyle(
                                        fontSize: 16,
                                        color: Colors.black,
                                        fontWeight: FontWeight.bold)),
                              ],
                            ),
                            onTap: () {
                              setState(() {
                                _unDelaySelected = false;
                                _delaySelected = true;
                              });
                            },
                          ),
                        ],
                      ),
                      Visibility(
                        visible: _unDelaySelected,
                        child: buildColumnDelivery(),
                      ),
                      Visibility(
                        visible: _delaySelected,
                        child: GestureDetector(
                          child: Container(
                            color: Colors.white,
                            padding: EdgeInsets.symmetric(vertical: 10),
                            child: Row(
                              children: [
                                Text('*预估发货时间：',style: TextStyle(fontWeight: FontWeight.bold),),
                                SizedBox(
                                  width: 10,
                                ),
                                Expanded(
                                    child: Text(
                                      timeStr==null?'请选择时间':timeStr,
                                      style: TextStyle(color: timeStr==null?Colors.grey:Colors.black),
                                    )),
                                Icon(
                                  Icons.chevron_right,
                                  color: Colors.grey,
                                )
                              ],
                            ),
                          ),
                          onTap: () {
                            MyPicker.showPicker(
                              context: context,
                              current: DateTime.now(),
                              end: DateTime.now(),
                              mode: MyPickerMode.date,
                              onConfirm: (_date) {
                                print('confirm$_date');
                                timeStr=MyDate.format('yyyy-MM-dd', _date);
                                setState(() {

                                });
                              },
                            );
                          },
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ):buildColumnDelivery(),
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('审核备注：',
                    textAlign: TextAlign.end,
                    style: TextStyle(
                        fontSize: 16,
                        color: Colors.black,
                        fontWeight: FontWeight.bold)),
                SizedBox(height: 10),
                TextField(
                  controller: checkRemarksCtr,
                  maxLines: 5,
                  decoration: InputDecoration(
                      hintText: '请输入审核备注',
                      contentPadding: EdgeInsets.all(10),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(5.0),
                      )),
                ),
              ],
            ),
          ],
        ));
  }

  Column buildColumnDelivery() {
    return Column(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          // 复选框
                          GestureDetector(
                            child: Row(
                              children: [
                                Checkbox(
                                    value: _workerSelected,
                                    onChanged: (value) {
                                      setState(() {
                                        _workerSelected = true;
                                        _userSelected = false;
                                        SendAddress=workAddr;
                                      });
                                    }),
                                Text('师傅收件',
                                    textAlign: TextAlign.end,
                                    style: TextStyle(
                                        fontSize: 16,
                                        color: Colors.black,
                                        fontWeight: FontWeight.bold)),
                              ],
                            ),
                            onTap: () {
                              setState(() {
                                _workerSelected = true;
                                _userSelected = false;
                                SendAddress=workAddr;
                              });
                            },
                          ),
                          GestureDetector(
                            child: Row(
                              children: [
                                Checkbox(
                                    value: _userSelected,
                                    onChanged: (value) {
                                      setState(() {
                                        _workerSelected = false;
                                        _userSelected = true;
                                        SendAddress=userAddr;
                                      });
                                    }),
                                Text('用户收件',
                                    textAlign: TextAlign.end,
                                    style: TextStyle(
                                        fontSize: 16,
                                        color: Colors.black,
                                        fontWeight: FontWeight.bold)),
                              ],
                            ),
                            onTap: () {
                              setState(() {
                                _workerSelected = false;
                                _userSelected = true;
                                SendAddress=userAddr;
                              });
                            },
                          ),
                        ],
                      ),
                      Text(
                          _workerSelected
                              ? workAddr
                              : userAddr,
                          textAlign: TextAlign.left,
                          style: TextStyle(
                              fontSize: 16,
                              color: Colors.red,
                              fontWeight: FontWeight.bold)),
                      Column(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              // 复选框
                              GestureDetector(
                                child: Row(
                                  children: [
                                    Checkbox(
                                        value: _yesSelected,
                                        onChanged: (value) {
                                          setState(() {
                                            _yesSelected = true;
                                            _noSelected = false;
                                          });
                                        }),
                                    Text('需要返件',
                                        textAlign: TextAlign.end,
                                        style: TextStyle(
                                            fontSize: 16,
                                            color: Colors.black,
                                            fontWeight: FontWeight.bold)),
                                  ],
                                ),
                                onTap: () {
                                  setState(() {
                                    _yesSelected = true;
                                    _noSelected = false;
                                  });
                                },
                              ),
                              GestureDetector(
                                child: Row(
                                  children: [
                                    Checkbox(
                                        value: _noSelected,
                                        onChanged: (value) {
                                          setState(() {
                                            _yesSelected = false;
                                            _noSelected = true;
                                          });
                                        }),
                                    Text('不需要返件',
                                        textAlign: TextAlign.end,
                                        style: TextStyle(
                                            fontSize: 16,
                                            color: Colors.black,
                                            fontWeight: FontWeight.bold)),
                                  ],
                                ),
                                onTap: () {
                                  setState(() {
                                    _yesSelected = false;
                                    _noSelected = true;
                                  });
                                },
                              ),
                            ],
                          ),
                          Visibility(
                            visible: _yesSelected,
                            child: Column(
                              children: [
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  children: [
                                    // 复选框
                                    GestureDetector(
                                      child: Row(
                                        children: [
                                          Checkbox(
                                              value: _xSelected,
                                              onChanged: (value) {
                                                setState(() {
                                                  _xSelected = true;
                                                  _dSelected = false;
                                                });
                                              }),
                                          Text('师傅现付',
                                              textAlign: TextAlign.end,
                                              style: TextStyle(
                                                  fontSize: 16,
                                                  color: Colors.black,
                                                  fontWeight: FontWeight.bold)),
                                        ],
                                      ),
                                      onTap: () {
                                        setState(() {
                                          _xSelected = true;
                                          _dSelected = false;
                                        });
                                      },
                                    ),
                                    GestureDetector(
                                      child: Row(
                                        children: [
                                          Checkbox(
                                              value: _dSelected,
                                              onChanged: (value) {
                                                setState(() {
                                                  _xSelected = false;
                                                  _dSelected = true;
                                                });
                                              }),
                                          Text('工厂到付',
                                              textAlign: TextAlign.end,
                                              style: TextStyle(
                                                  fontSize: 16,
                                                  color: Colors.black,
                                                  fontWeight: FontWeight.bold)),
                                        ],
                                      ),
                                      onTap: () {
                                        setState(() {
                                          _xSelected = false;
                                          _dSelected = true;
                                        });
                                      },
                                    ),
                                  ],
                                ),
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text('返件地址：',
                                        textAlign: TextAlign.end,
                                        style: TextStyle(
                                            fontSize: 16,
                                            color: Colors.black,
                                            fontWeight: FontWeight.bold)),
                                    Expanded(
                                      child: buildDropdownButton(),
                                    ),
                                  ],
                                ),
                                SizedBox(height: 10),
                                Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text('旧件返件要求：',
                                        textAlign: TextAlign.end,
                                        style: TextStyle(
                                            fontSize: 16,
                                            color: Colors.black,
                                            fontWeight: FontWeight.bold)),
                                    SizedBox(height: 10),
                                    TextField(
                                      controller: oldReturnRequestCtr,
                                      maxLines: 5,
                                      decoration: InputDecoration(
                                          hintText: '请输入旧件返件要求',
                                          contentPadding: EdgeInsets.all(10),
                                          border: OutlineInputBorder(
                                            borderRadius: BorderRadius.circular(5.0),
                                          )),
                                    ),
                                  ],
                                ),
                              ],
                            ),
                          ),
                          SizedBox(height: 20),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text('*物流单号：',
                                  textAlign: TextAlign.end,
                                  style: TextStyle(
                                      fontSize: 16,
                                      color: Colors.black,
                                      fontWeight: FontWeight.bold)),
                              Expanded(
                                child: TextField(
                                  controller: expressNoCtr,
                                  maxLines: 1,
                                  decoration: InputDecoration(
                                      hintText: '请输入物流单号',
                                      contentPadding: EdgeInsets.all(10),
                                      border: OutlineInputBorder(
                                        borderRadius: BorderRadius.circular(5.0),
                                      )),
                                ),
                              ),
                              SizedBox(width: 10),
                              RaisedButton(onPressed: () {
                                _scan();
                              }, child: Text('扫描'))
                            ],
                          ),
                        ],
                      ),
                    ],
                  );
  }

  DropdownButton buildDropdownButton() {
    return DropdownButton(
        isExpanded: true,
        // 隐藏下划线
        underline: Container(height: 0),
        value: AddressBack,
        items: items.map((item){
          return DropdownMenuItem(
              child: Text(item.name), value: '${item.value}');
        }).toList(),
        onChanged: (value) {
          setState(() {
            AddressBack=value;
            print(value);
          });
        });
  }
}
